<?php

namespace Trawind\ConfigCenter\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
use Trawind\Basics\Commands\SystemDownCommand;
use Trawind\ConfigCenter\Helpers\ConfigHelper;
use Trawind\Helpers\HttpClientHelper;
use Trawind\Helpers\SystemHelper;

class ConfigVersion
{

    const USER_CONFIG = 'user_config';


    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $request->headers->set('Accept', 'application/json');
        if (HttpClientHelper::isRemoteRequest()) {
            return $next($request);
        }
        
        $this->checkForMaintenanceMode();
        $this->loadUserConfig();

        /**
         * @var JsonResponse $response
         */
        $response = $next($request);

        $lastTime = Redis::hget(ConfigHelper::userKey(), 'last_time');
        $response->header('last-time', $lastTime);

        return $response;
    }


    public function loadUserConfig()
    {
        $userConfig = ConfigHelper::userConfig();

        config(['app.locale' => $userConfig['language'] ?? 'zh_CN']);
        app()->bind(static::USER_CONFIG, function () use ($userConfig) {
            return $userConfig;
        });
    }


    public function loadCommonConfig()
    {
        $commonConfig = ConfigHelper::commonConfig(ConfigHelper::SYSTEM_DEFAULT);

        config(['app.locale' => $commonConfig['language'] ?? 'zh_CN']);
        app()->bind(static::USER_CONFIG, function () use ($commonConfig) {
            return $commonConfig;
        });
    }


    public function checkForMaintenanceMode()
    {
        if ($content = SystemHelper::redis()->get(SystemDownCommand::DOWN_KEY)) {
            $ttl = SystemHelper::redis()->ttl(SystemDownCommand::DOWN_KEY);
            throw new ServiceUnavailableHttpException($ttl, $content."({$ttl}s)");
        }
    }

}
